from pynput import mouse
import threading
from PySide6.QtWidgets import QApplication, QMainWindow
from PySide6.QtCore import Qt


class MouseListener:
    def __init__(self, callback=None):
        self._callback = callback
        self._maskWindows = []

    def startListen(self):
        self._maskWindows = []
        screens = QApplication.instance().screens()
        for screen in screens:
            window = QMainWindow()
            screenGeometry = screen.geometry()
            window.setGeometry(screenGeometry.x(), screenGeometry.y(), screenGeometry.width(), screenGeometry.height())
            window.setWindowOpacity(0.01)
            window.showMaximized()
            window.setWindowFlag(Qt.WindowType.WindowStaysOnTopHint)
            self._maskWindows.append(window)

        for window in self._maskWindows:
            window.show()

        r = threading.Thread(target=self.listenThread)
        r.start()

    def listenThread(self):
        with mouse.Listener(on_click=self.callback) as listener:
            listener.join()
            listener.stop()

    def callback(self, x, y, button, pressed):
        result = self._callback(x, y, button, pressed)
        if result == False:
            for window in self._maskWindows:
                window.deleteLater()

            return result
